# coding:utf-8
class Admin::ReportGroupsController < AdminController

  set_tab :reports
  before_filter :setup, only: [:index, :flow_report, :tev]

  def index
    set_tab :report_group, :sub_nav
    @ways = ["报表","用户统计"]
    params[:report] ||= {}
    @terminals = []
    if params[:report].present?
      params[:report][:date_part] = 'day' unless params[:report][:date_part]
      date_range()
      @register_chart_attrs = get_register_line_chart_attrs
      @signin_chart_attrs = get_signin_line_chart_attrs
    end
  end

  def tev
    set_tab :tev, :sub_nav
    @ways = ["报表","收视统计"]
    params[:report] ||= {}
    if params[:report].present?
      date_range()
      params[:report][:date_part] = 'day' unless params[:report][:date_part]
      @watching_line_chart1_attrs, @watching_line_chart2_attrs, @watching_line_chart3_attrs = get_watching_line_chart1_attrs
    end
  end

  def flow_report
    set_tab :flow_report, :sub_nav
    @ways = ["报表","3G流量查询"]
    params[:report] ||= {}
  end

  def city_changed
    terminal_groups = TerminalGroup
    terminal_groups = terminal_groups.where(city_id: params[:city]) if params[:city].present?
    industries = terminal_groups.uniq.pluck('industry').compact
    industry_options = "<option value="">全部</option>" + industries.map{|i| "<option value='#{i}'>#{i}</option>" }.join
    group_names = terminal_groups.uniq.pluck('group_name').compact
    group_name_options = "<option value="">全部</option>" + group_names.map{|i| "<option value='#{i}'>#{i}</option>" }.join
    terminals = Terminal.where(["terminal_group_id in (?)",terminal_groups.all.map(&:id)]).pluck('mac').compact
    terminal_options = "<option value="">全部</option>" + terminals.map{|i| "<option value='#{i}'>#{i}</option>" }.join
    render :text => [industry_options,group_name_options,terminal_options].join(" and ")
  end

  def industry_changed
    terminal_groups = TerminalGroup
    terminal_groups = terminal_groups.where(city_id: params[:city]) if params[:city].present?
    terminal_groups = terminal_groups.where(industry: params[:industry]) if params[:industry].present?
    group_names = terminal_groups.uniq.pluck('group_name').compact
    group_name_options = "<option value="">全部</option>" + group_names.map{|i| "<option value='#{i}'>#{i}</option>" }.join
    terminals = Terminal.where(["terminal_group_id in (?)",terminal_groups.all.map(&:id)]).pluck('mac').compact
    terminal_options = "<option value="">全部</option>" + terminals.map{|i| "<option value='#{i}'>#{i}</option>" }.join
    render :text => [group_name_options,terminal_options].join(" and ")
  end

  def group_name_changed
    terminal_groups = TerminalGroup
    terminal_groups = terminal_groups.where(city_id: params[:city]) if params[:city].present?
    terminal_groups = terminal_groups.where(industry: params[:industry]) if params[:industry].present?
    terminal_groups = terminal_groups.where(group_name: params[:group_name]) if params[:group_name].present?
    group_names = terminal_groups.uniq.pluck('group_name').compact
    group_name_options = "<option value="">全部</option>" + group_names.map{|i| "<option value='#{i}'>#{i}</option>" }.join
    terminals = Terminal.where(["terminal_group_id in (?)",terminal_groups.all.map(&:id)]).pluck('mac').compact
    terminal_options = "<option value="">全部</option>" + terminals.map{|i| "<option value='#{i}'>#{i}</option>" }.join
    render :text => terminal_options
  end

  private

  def setup
    @left_panel = "layouts/report_groups"
  end

  def date_range
    @start_date = nil
    @end_date = nil

    if params[:report][:start_date].blank? && params[:report][:end_date].blank?
      case params[:report][:date_part]
      when 'day'
        @start_date = 14.days.ago(Date.today)
        @end_date = Date.today
        @range = (@end_date - @start_date).to_i
      when 'month'
        @start_date = 14.months.ago(Date.today.beginning_of_month)
        @end_date = Date.today
        @range = (@end_date.year - @start_date.year) * 12 + @end_date.month - @start_date.month
      when 'year'
        @start_date = 14.years.ago(Date.today.beginning_of_year)
        @end_date = Date.today
        @range = @end_date.year - @start_date.year
      end
    elsif !params[:report][:start_date].blank? && params[:report][:end_date].blank?
      @start_date = params[:report][:start_date].to_date
      case params[:report][:date_part]
      when 'day'
        if 15.days.since(@start_date) > Date.today
          @end_date = Date.today
        else
          @end_date = 15.days.since(@start_date)
        end
        @range = (@end_date - @start_date).to_i
      when 'month'
        if 15.months.since(@start_date) > Date.today
          @end_date = Date.today
        else
          @end_date = 15.months.since(@start_date)
        end
        @range = (@end_date.year - @start_date.year) * 12 + @end_date.month - @start_date.month
      when 'year'
        if 15.years.since(@start_date) > Date.today
          @end_date = Date.today
        else
          @end_date = 15.years.since(@start_date)
        end
        @range = @end_date.year - @start_date.year
      end
    elsif params[:report][:start_date].blank? && !params[:report][:end_date].blank?
      @end_date = params[:report][:end_date].to_date
      case params[:report][:date_part]
      when 'day'
        @start_date = 15.days.ago(@end_date)
        @range = (@end_date - @end_date).to_i
      when 'month'
        @start_date = 15.months.ago(@end_date)
        @range = (@end_date.year - @start_date.year) * 12 + @end_date.month - @start_date.month
      when 'year'
        @start_date = 15.years.ago(@end_date)
        @range = @end_date.year - @start_date.year
      end
    else
      @start_date = params[:report][:start_date].to_date
      @end_date = params[:report][:end_date].to_date
      if @end_date > Date.today
        @end_date = Date.today
      end
      case params[:report][:date_part]
      when 'day'
        if 15.days.since(@start_date) < @end_date
          @end_date = 15.days.since(@start_date)
        end
        @range = (@end_date - @start_date).to_i
      when 'month'
        if 15.months.since(@start_date) < @end_date
          @end_date = 15.months.since(@start_date)
        end
        @range = (@end_date.year - @start_date.year) * 12 + @end_date.month - @start_date.month
      when 'year'
        if 15.years.since(@start_date) < @end_date
          @end_date = 15.years.since(@start_date)
        end
        @range = @end_date.year - @start_date.year
      end
    end
    @range = @range + 1
  end

  def get_register_line_chart_attrs
    chart_attrs = {:type => 'line'}
    chart_attrs[:title] = "新注册用户(#{date_parts[params[:report][:date_part]]})"
    chart_attrs[:name] = "新注册用户(#{date_parts[params[:report][:date_part]]})"
    chart_attrs[:min_width] = 530
    chart_attrs[:uom] = ''
    chart_attrs[:xaxis] = []

    accounts = Account
    accounts = accounts.joins(:register_terminal => {:terminal_group => {}}).where(["terminal_groups.city_id = ?",params[:report][:city]]) if params[:report][:city].present?
    accounts = accounts.joins(:register_terminal => {:terminal_group => {}}).where(["terminal_groups.industry = ?",params[:report][:industry]]) if params[:report][:industry].present?
    accounts = accounts.joins(:register_terminal => {:terminal_group => {}}).where(["terminal_groups.group_name = ?",params[:report][:group_name]]) if params[:report][:group_name].present?
    accounts = accounts.joins(:register_terminal).where(["terminals.mac = ?",params[:report][:terminal]]) if params[:report][:terminal].present?

    case params[:report][:date_part]
    when 'day'
      (@start_date..@end_date).each do |iday|
        chart_attrs[:xaxis] << iday
      end
      accounts = accounts.where(["accounts.firsted_signin >= ? and accounts.firsted_signin <= ?",@start_date,1.days.since(@end_date)])
      accounts = accounts.group("DATE(accounts.firsted_signin)")
      chart_attrs[:datas] = {"新注册用户" => Array.new(@range){0}}
      accounts.select("DATE(accounts.firsted_signin) as created_part,count(accounts.id) as total").each do |acg|
        chart_attrs[:datas]["新注册用户"][chart_attrs[:xaxis].index(Date.parse(acg.created_part))] = acg.total
      end
    when 'month'
      t_month = @start_date
      while t_month.strftime("%Y-%m") <= @end_date.strftime("%Y-%m") do
        chart_attrs[:xaxis] << t_month.strftime("%Y-%m").to_s
        t_month = t_month.next_month
      end
      accounts = accounts.where(["accounts.firsted_signin >= ? and accounts.firsted_signin <= ?",@start_date,1.days.since(@end_date)])
      accounts = accounts.group("EXTRACT(YEAR from accounts.firsted_signin),EXTRACT(MONTH from accounts.firsted_signin)")
      chart_attrs[:datas] = {"新注册用户" => Array.new(@range){0}}
      accounts.select("EXTRACT(YEAR from accounts.firsted_signin) as created_year,EXTRACT(MONTH from accounts.firsted_signin) as created_part,count(accounts.id) as total").each do |acg|
        chart_attrs[:datas]["新注册用户"][chart_attrs[:xaxis].index(Date.new(acg.created_year.to_i,acg.created_part.to_i).strftime("%Y-%m"))] = acg.total
      end
    when 'year'
      t_month = @start_date
      while t_month.strftime("%Y") <= @end_date.strftime("%Y") do
        chart_attrs[:xaxis] << t_month.strftime("%Y").to_s
        t_month = t_month.next_year
      end
      accounts = accounts.where(["accounts.firsted_signin >= ? and accounts.firsted_signin <= ?",@start_date,1.days.since(@end_date)])
      accounts = accounts.group("EXTRACT(YEAR from accounts.firsted_signin)")
      chart_attrs[:datas] = {"新注册用户" => Array.new(@range){0}}
      accounts.select("EXTRACT(YEAR from accounts.firsted_signin) as created_part,count(accounts.id) as total").each do |acg|
        chart_attrs[:datas]["新注册用户"][chart_attrs[:xaxis].index(Date.new(acg.created_part.to_i).strftime("%Y"))] = acg.total
      end
    end
    chart_attrs
  end

  def get_signin_line_chart_attrs
    chart_attrs = {:type => 'line'}
    chart_attrs[:title] = "签到记录(#{date_parts[params[:report][:date_part]]})"
    chart_attrs[:name] = "签到记录(#{date_parts[params[:report][:date_part]]})"
    chart_attrs[:min_width] = 530
    chart_attrs[:uom] = ''
    chart_attrs[:xaxis] = []

    asscount_signins = AccountSignin
    asscount_signins = asscount_signins.joins(:terminal => {:terminal_group => {}}).where(["terminal_groups.city_id = ?",params[:report][:city]]) if params[:report][:city].present?
    asscount_signins = asscount_signins.joins(:terminal => {:terminal_group => {}}).where(["terminal_groups.industry = ?",params[:report][:industry]]) if params[:report][:industry].present?
    asscount_signins = asscount_signins.joins(:terminal => {:terminal_group => {}}).where(["terminal_groups.group_name = ?",params[:report][:group_name]]) if params[:report][:group_name].present?
    asscount_signins = asscount_signins.joins(:terminal).where(["terminals.mac = ?",params[:report][:terminal]]) if params[:report][:terminal].present?

    case params[:report][:date_part]
    when 'day'
      (@start_date..@end_date).each do |iday|
        chart_attrs[:xaxis] << iday
      end
      asscount_signins = asscount_signins.where(["account_signins.created_at >= ? and account_signins.created_at <= ?",@start_date,1.days.since(@end_date)])
      asscount_signins = asscount_signins.group("DATE(account_signins.created_at)")
      chart_attrs[:datas] = {"签到记录" => Array.new(@range){0}}
      asscount_signins.select("DATE(account_signins.created_at) as created_part,count(account_signins.id) as total").each do |acg|
        chart_attrs[:datas]["签到记录"][chart_attrs[:xaxis].index(Date.parse(acg.created_part))] = acg.total
      end
    when 'month'
      t_month = @start_date
      while t_month.strftime("%Y-%m") <= @end_date.strftime("%Y-%m") do
        chart_attrs[:xaxis] << t_month.strftime("%Y-%m").to_s
        t_month = t_month.next_month
      end
      asscount_signins = asscount_signins.where(["account_signins.created_at >= ? and account_signins.created_at <= ?",@start_date,1.days.since(@end_date)])
      asscount_signins = asscount_signins.group("EXTRACT(YEAR from account_signins.created_at),EXTRACT(MONTH from account_signins.created_at)")
      chart_attrs[:datas] = {"签到记录" => Array.new(@range){0}}
      asscount_signins.select("EXTRACT(YEAR from account_signins.created_at) as created_year,EXTRACT(MONTH from account_signins.created_at) as created_part,count(account_signins.id) as total").each do |acg|
        chart_attrs[:datas]["签到记录"][chart_attrs[:xaxis].index(Date.new(acg.created_year.to_i,acg.created_part.to_i).strftime("%Y-%m"))] = acg.total
      end
    when 'year'
      t_month = @start_date
      while t_month.strftime("%Y") <= @end_date.strftime("%Y") do
        chart_attrs[:xaxis] << t_month.strftime("%Y").to_s
        t_month = t_month.next_year
      end
      asscount_signins = asscount_signins.where(["account_signins.created_at >= ? and account_signins.created_at <= ?",@start_date,1.days.since(@end_date)])
      asscount_signins = asscount_signins.group("EXTRACT(YEAR from account_signins.created_at),EXTRACT(MONTH from account_signins.created_at)")
      chart_attrs[:datas] = {"签到记录" => Array.new(@range){0}}
      asscount_signins.select("EXTRACT(YEAR from account_signins.created_at) as created_part,count(account_signins.id) as total").each do |acg|
        chart_attrs[:datas]["签到记录"][chart_attrs[:xaxis].index(Date.new(acg.created_part.to_i).strftime("%Y"))] = acg.total
      end
    end
    chart_attrs
  end

  def get_watching_line_chart1_attrs
    chart_attrs = {:type => 'line',:labelname => '收视率', uom: '次'}
    chart2_attrs = {:type => 'line',:labelname => '收视率', uom: '小时'}
    chart3_attrs = {:type => 'line',:labelname => '平均时长', uom: '小时'}
    chart_attrs[:min_width] = 530
    chart2_attrs[:min_width] = 530
    chart3_attrs[:min_width] = 530
    chart_attrs[:datas] = {}
    chart_attrs[:xaxis] = []
    chart2_attrs[:datas] = {}
    chart2_attrs[:xaxis] = []
    chart3_attrs[:datas] = {}
    chart3_attrs[:xaxis] = []

    watchings = Watching
    case params[:report][:date_part]
    when 'day'
      chart_attrs[:title] = "收视率(次数)从#{@start_date}到#{@end_date}"
      chart2_attrs[:title] = "收视率(时长)从#{@start_date}到#{@end_date}"
      chart3_attrs[:title] = "收视率(平均时长)从#{@start_date}到#{@end_date}"
      watchings.where(["watchings.created_at >= ? and watchings.created_at <= ?",@start_date,1.days.since(@end_date)])
    when 'month'
      chart_attrs[:title] = "收视率(次数)从#{@start_date.strftime("%Y-%m")}到#{@end_date.strftime("%Y-%m")}"
      chart2_attrs[:title] = "收视率(时长)从#{@start_date.strftime("%Y-%m")}到#{@end_date.strftime("%Y-%m")}"
      chart3_attrs[:title] = "收视率(平均时长)从#{@start_date.strftime("%Y-%m")}到#{@end_date.strftime("%Y-%m")}"
      watchings.where(["watchings.created_at >= ? and watchings.created_at <= ?",@start_date,1.days.since(@end_date)])
    when 'year'
      chart_attrs[:title] = "收视率(次数)从#{@start_date.strftime("%Y")}到#{@end_date.strftime("%Y")}"
      chart2_attrs[:title] = "收视率(时长)从#{@start_date.strftime("%Y")}到#{@end_date.strftime("%Y")}"
      chart2_attrs[:title] = "收视率(平均时长)从#{@start_date.strftime("%Y")}到#{@end_date.strftime("%Y")}"
      watchings.where(["watchings.created_at >= ? and watchings.created_at <= ?",@start_date,1.days.since(@end_date)])
    end

    case params[:report][:date_part]
    when 'day'
      (@start_date..@end_date).each do |iday|
        chart_attrs[:xaxis] << iday
        chart2_attrs[:xaxis] << iday
        chart3_attrs[:xaxis] << iday
      end
      watchings = watchings.where(["watchings.created_at >= ? and watchings.created_at <= ?",@start_date,1.days.since(@end_date)]).all
      
      watchings.group_by(&:television_name).each do |television_name,watching_g|
        chart_attrs[:datas][television_name] = Array.new(@range){0} unless chart_attrs[:datas][television_name]
        chart2_attrs[:datas][television_name] = Array.new(@range){0} unless chart2_attrs[:datas][television_name]
        chart3_attrs[:datas][television_name] = Array.new(@range){0} unless chart3_attrs[:datas][television_name]
        watching_g.group_by{|w| w.created_at.to_date }.each do |d,wg|
          windx = chart_attrs[:xaxis].index(d)
          chart_attrs[:datas][television_name][windx] = wg.size
          chart2_attrs[:datas][television_name][windx] = (wg.map(&:seconds).sum.to_f/3600).round(2)
          chart3_attrs[:datas][television_name][windx] = (chart2_attrs[:datas][television_name][windx]/wg.size).round(2) if wg.size > 0
        end
      end
    when 'month'
      t_month = @start_date
      while t_month.strftime("%Y-%m") <= @end_date.strftime("%Y-%m") do
        chart_attrs[:xaxis] << t_month.strftime("%Y-%m")
        chart2_attrs[:xaxis] << t_month.strftime("%Y-%m")
        chart3_attrs[:xaxis] << t_month.strftime("%Y-%m")
        t_month = t_month.next_month
      end
      watchings = watchings.where(["watchings.created_at >= ? and watchings.created_at <= ?",@start_date,1.days.since(@end_date)]).all
      
      watchings.group_by(&:television_name).each do |television_name,watching_g|
        chart_attrs[:datas][television_name] = Array.new(@range){0} unless chart_attrs[:datas][television_name]
        chart2_attrs[:datas][television_name] = Array.new(@range){0} unless chart2_attrs[:datas][television_name]
        chart3_attrs[:datas][television_name] = Array.new(@range){0} unless chart3_attrs[:datas][television_name]
        watching_g.group_by{|w| w.created_at.to_date.strftime("%Y-%m") }.each do |d,wg|
          windx = chart_attrs[:xaxis].index(d)
          chart_attrs[:datas][television_name][windx] = wg.size
          chart2_attrs[:datas][television_name][windx] = (wg.map(&:seconds).sum.to_f/3600).round(2)
          chart3_attrs[:datas][television_name][windx] = (chart2_attrs[:datas][television_name][windx]/wg.size).round(2) if wg.size > 0
        end
      end
    when 'year'
      t_month = @start_date
      while t_month.strftime("%Y") <= @end_date.strftime("%Y") do
        chart_attrs[:xaxis] << t_month.strftime("%Y")
        chart2_attrs[:xaxis] << t_month.strftime("%Y")
        chart3_attrs[:xaxis] << t_month.strftime("%Y")
        t_month = t_month.next_year
      end
      watchings = watchings.where(["watchings.created_at >= ? and watchings.created_at <= ?",@start_date,1.days.since(@end_date)]).all
      
      watchings.group_by(&:television_name).each do |television_name,watching_g|
        chart_attrs[:datas][television_name] = Array.new(@range){0} unless chart_attrs[:datas][television_name]
        chart2_attrs[:datas][television_name] = Array.new(@range){0} unless chart2_attrs[:datas][television_name]
        chart3_attrs[:datas][television_name] = Array.new(@range){0} unless chart3_attrs[:datas][television_name]
        watching_g.group_by{|w| w.created_at.to_date.strftime("%Y") }.each do |d,wg|
          windx = chart_attrs[:xaxis].index(d)
          chart_attrs[:datas][television_name][windx] = wg.size
          chart2_attrs[:datas][television_name][windx] = (wg.map(&:seconds).sum.to_f/3600).round(2)
          chart3_attrs[:datas][television_name][windx] = (chart2_attrs[:datas][television_name][windx]/wg.size).round(2) if wg.size > 0
        end
      end
    end

    return chart_attrs, chart2_attrs, chart3_attrs
  end

end